package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.GmWaterRateMapper;
import com.ruoyi.system.service.IGmWaterRateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

@Service
public class GmWaterRateServiceImpl implements IGmWaterRateService {

    @Autowired
    private GmWaterRateMapper gmWaterRateMapper;

    @Autowired
    private SysFloorServiceImpl sysFloorService;

    @Override
    public List<GmWaterRate> getGmWaterRateList(GmWaterRate gmWaterRate) {
        return gmWaterRateMapper.getGmWaterRateList(gmWaterRate);
    }

    @Override
    public GmWaterRate selectWaterRateByFloorAndEtldt(GmWaterRate gmWaterRate) {
        return gmWaterRateMapper.selectWaterRateByFloorAndEtldt(gmWaterRate);
    }

    @Override
    public int insertWaterRate(GmWaterRate gmWaterRate) {
        countTotalData(gmWaterRate);
        gmWaterRate.setAmmeterId(UUID.randomUUID().toString().replaceAll("-",""));
//        gmWaterRate.setEtldt(getMonth(gmWaterRate.getIssueDate()));
//        gmWaterRate.setEtldt(gmWaterRate.getEtldt());
        return gmWaterRateMapper.insertWaterRate(gmWaterRate);
    }

    private void countTotalData(GmWaterRate gmWaterRate) {
        BigDecimal degreeAbd = new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueA())).subtract(new BigDecimal(Double.toString(gmWaterRate.getDegreePreA())));
        Double degreeA = degreeAbd.doubleValue();
        BigDecimal degreeBbd = new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueB())).subtract(new BigDecimal(Double.toString(gmWaterRate.getDegreePreB())));
        Double degreeB = degreeBbd.doubleValue();
        BigDecimal degreeCbd = new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueC())).subtract(new BigDecimal(Double.toString(gmWaterRate.getDegreePreC())));
        Double degreeC = degreeCbd.doubleValue();
        BigDecimal degreeDbd = new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueD())).subtract(new BigDecimal(Double.toString(gmWaterRate.getDegreePreD())));
        Double degreeD = degreeDbd.doubleValue();
        /*上月水表总度数*/
        BigDecimal degreePrebd = new BigDecimal(Double.toString(gmWaterRate.getDegreePreA())).add(new BigDecimal(Double.toString(gmWaterRate.getDegreePreB()))).add(new BigDecimal(Double.toString(gmWaterRate.getDegreePreC()))).add(new BigDecimal(Double.toString(gmWaterRate.getDegreePreD())));
        Double degreePre = degreePrebd.doubleValue();
        /*本月水表总度数*/
        BigDecimal degreeIssuebd = new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueA())).add(new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueB()))).add(new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueC()))).add(new BigDecimal(Double.toString(gmWaterRate.getDegreeIssueD())));
        Double degreeIssue = degreeIssuebd.doubleValue();
        /*总度数*/
        BigDecimal degreebd = degreeIssuebd.subtract(degreePrebd);
        Double degree = degreebd.doubleValue();
        /*水费*/
        BigDecimal amountMoneybd = new BigDecimal(Double.toString(gmWaterRate.getMultiplicationTerm())).multiply(new BigDecimal(Double.toString(gmWaterRate.getUnitPrice()))).multiply(degreebd);
        Double amountMoney = amountMoneybd.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        /*将值塞入实体类*/
        gmWaterRate.setDegreeA(degreeA);
        gmWaterRate.setDegreeB(degreeB);
        gmWaterRate.setDegreeC(degreeC);
        gmWaterRate.setDegreeD(degreeD);
        gmWaterRate.setDegreePre(degreePre);
        gmWaterRate.setDegreeIssue(degreeIssue);
        gmWaterRate.setDegree(degree);
        gmWaterRate.setAmountMoney(amountMoney);
    }


    @Override
    public GmWaterRate getWaterRateById(String ammeterId) {
        return gmWaterRateMapper.getWaterRateById(ammeterId);
    }

    @Override
    public int updateWaterRate(GmWaterRate gmWaterRate) {
        countTotalData(gmWaterRate);
//        gmWaterRate.setEtldt(getMonth(gmWaterRate.getIssueDate()));
        return gmWaterRateMapper.updateWaterRate(gmWaterRate);
    }

    @Override
    public int removeWaterRate(String ids) {
        String[] ammeterIds = Convert.toStrArray(ids);
        return gmWaterRateMapper.removeWaterRate(ammeterIds);
    }



    @Override
    public List<GmWaterRate> selectWaterCostByEtldt(String etldt) {
        return gmWaterRateMapper.selectWaterCostByEtldt(etldt);
    }

    @Override
    public List<GmWaterRate> selectWaterCostByUName(String unitName) {
        return gmWaterRateMapper.selectWaterCostByUName(unitName);
    }

    @Override
    public String validateDatas(List<GmWaterRateExcel> lists) {
        StringBuilder sb =new StringBuilder();
        String regex = "^(20|19){1}[0-9]{2}(((0){1}[1-9]{1})|((1){1}(0|1|2){1}))$";
        if (StringUtils.isEmpty(lists)){
            sb.append("excel中无任何数据，请确认文件！");
        }else {
            for (int i = 0; i <lists.size() ; i++) {
                /* ABCD抄表无数据null填充 */
                if (lists.get(i).getDegreePreA() == null){
                    lists.get(i).setDegreePreA(0.0);
                }
                if (lists.get(i).getDegreePreB() == null){
                    lists.get(i).setDegreePreB(0.0);
                }
                if (lists.get(i).getDegreePreC() == null){
                    lists.get(i).setDegreePreC(0.0);
                }
                if (lists.get(i).getDegreePreD() == null){
                    lists.get(i).setDegreePreD(0.0);
                }
                if (lists.get(i).getDegreeIssueA() == null){
                    lists.get(i).setDegreeIssueA(0.0);
                }
                if (lists.get(i).getDegreeIssueB() == null){
                    lists.get(i).setDegreeIssueB(0.0);
                }
                if (lists.get(i).getDegreeIssueC() == null){
                    lists.get(i).setDegreeIssueC(0.0);
                }
                if (lists.get(i).getDegreeIssueD() == null){
                    lists.get(i).setDegreeIssueD(0.0);
                }
                /* 数据判断 */
                if (StringUtils.isBlank(lists.get(i).getProjectName())){
                    sb.append("第"+(i+1)+"行、项目名称为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getUnitName())){
                    sb.append("第"+(i+1)+"行、用户单位名称为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getFloorName())){
                    sb.append("第"+(i+1)+"行、楼层号为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getRoomNum())){
                    sb.append("第"+(i+1)+"行、房号为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getCheckMeterNum())){
                    sb.append("第"+(i+1)+"行、表号为空！<br/>");
                }
                if (StringUtils.isBlank(lists.get(i).getEtldt())){
                    sb.append("第"+(i+1)+"行、水费月份为空！<br/>");
                }
                if (!Pattern.matches(regex, lists.get(i).getEtldt())){
                    sb.append("第"+(i+1)+"行、水费月份不符合格式！<br/>");
                }
                if (!lists.get(0).getEtldt().equals(lists.get(i).getEtldt())){
                    sb.append("第"+(i+1)+"行、水费月份不符合导入的时间批次！<br/>");
                }
                if (Double.isNaN(lists.get(i).getMultiplicationTerm())){
                    sb.append("第"+(i+1)+"行、水费乘率为空！<br/>");
                }
                if (Double.isNaN(lists.get(i).getUnitPrice())){
                    sb.append("第"+(i+1)+"行、水费单价为空！<br/>");
                }
            }
        }
        if (sb.length()>0){
            return sb.toString();
        };
        return "";
    }

    @Override
    public String importRelations(List<GmWaterRateExcel> lists, boolean updateSupport, SysUser sysUser) {
        int successNum = 0;
        int failureNum = 0;
        StringBuffer successMsg = new StringBuffer();
        StringBuffer failureMsg = new StringBuffer();
        List<GmWaterRate> waterRateList = gmWaterRateMapper.selectAllWaterRate();
        List<String> list = new ArrayList<>();
        for (GmWaterRateExcel sb:lists) {
            GmWaterRate gm = new GmWaterRate();
            gm.setNum(sb.getNum());
            gm.setAmmeterId(sb.getAmmeterId());
            gm.setProjectName(sb.getProjectName());
            gm.setUnitName(sb.getUnitName());
            gm.setFloorName(sb.getFloorName());
            gm.setRoomNum(sb.getRoomNum());
            gm.setCheckMeterNum(sb.getCheckMeterNum());
            gm.setDegreePreA(sb.getDegreePreA());
            gm.setDegreeIssueA(sb.getDegreeIssueA());
            gm.setDegreePreB(sb.getDegreePreB());
            gm.setDegreeIssueB(sb.getDegreeIssueB());
            gm.setDegreePreC(sb.getDegreePreC());
            gm.setDegreeIssueC(sb.getDegreeIssueC());
            gm.setDegreePreD(sb.getDegreePreD());
            gm.setDegreeIssueD(sb.getDegreeIssueD());
            gm.setIssueDate(sb.getIssueDate());
            gm.setEtldt(sb.getEtldt());
//            gm.setEtldt(getMonth(gm.getIssueDate()));
            gm.setMultiplicationTerm(sb.getMultiplicationTerm());
            gm.setUnitPrice(sb.getUnitPrice());
            gm.setRemark(sb.getRemark());
            countTotalData(gm);
            if (StringUtils.isNotEmpty(gm.getAmmeterId())) {
                try{
                for (GmWaterRate ig : waterRateList) {
                    list.add(ig.getAmmeterId());
                }
                if (list.contains(gm.getAmmeterId())){
                    gmWaterRateMapper.updateWaterRate(gm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + gm.getAmmeterId() + "导入成功");
                }else{
                    gmWaterRateMapper.insertWaterRate(gm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + gm.getAmmeterId() + "导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、导入失败");
            }
            } else {
                try {
                    gm.setAmmeterId(UUID.randomUUID().toString().replaceAll("-", ""));
                    gmWaterRateMapper.insertWaterRate(gm);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + gm.getAmmeterId() + "导入成功");
                } catch (Exception e) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、导入失败");
                }
            }
        }
        if(failureNum > 0){
            failureMsg.insert(0, "很抱歉，导入失败！共"+failureNum+"条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }else {
            successMsg.insert(0, "恭喜您数据已全部导入成功！共"+ successNum +"条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 抽取年月时间
     */
    public String getMonth(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return new String(sdf.format(date));
    }

}
